<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>商品新增</title>
	<!-- 引入样式 -->
	<link rel="stylesheet" href="../../../../static/css/element.css" th:href="@{/css/element.css}">
	<link rel="stylesheet" href="../../../../static/css/global.css" th:href="@{/css/global.css}" />
	<link rel="stylesheet" href="../../../../static/css/main.css" th:href="@{/css/main.css}" />
	<link rel="stylesheet" href="../../../../static/css/myelement.css" th:href="@{/css/myelement.css}" />
	<!-- 引入组件库 -->
    <script src="../../../../static/js/vue.js" th:src="@{/js/vue.js}"></script>
    <script src="../../../../static/js/element.js" th:src="@{/js/element.js}"></script>
    <script src="../../../../static/js/jquery.min.js" th:src="@{/js/jquery.min.js}"></script>
    <script src="../../../../static/js/jquery.nestable.js" th:src="@{/js/jquery.nestable.js}"></script>
    <style type="text/css">
        [v-cloak] {
            display: none !important;
        }
    </style>
</head>
<body>
<div id="app">
    <div class="main-content">
        <!-- 页面头部 -->
        <div class="page-header">
            <h1 class="page-title">新增商品</h1>
            <div class="breadcrumb"><a href="##">首页</a><span>/</span><a href="##">商品管理</a><span>/</span><a href="##">商品新增</a></div>
        </div><!-- 页面头部 end -->

        <!-- 商品tab切换 -->
        <div class="z-tabs">
            <div class="z-tabs_header">
                <div class="z-tabs_item router-link-active">
                    <span class="item_span">基础</span>
                </div>
                <div class="z-tabs_item">
                    <span class="item_span">商品主图</span>
                </div>
            </div>
        </div><!-- 商品tab切换 end -->

        <div class="main-content-body no-pd-t tab-content">
            <!-- 商品基础信息 -->
            <div class="tab-pane active" id="productBasic"  v-cloak>
                <div class="edit-form title_pt_25">
                    <el-form :model="basicForm" :rules="basicRules" ref="basicForm" label-width="120px" class="demo-ruleForm">
                        <h3 class="edit-form-title">基础</h3>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="菜品名称" prop="name">
                                    <el-input v-model="basicForm.name" clearable  placeholder="商品名称"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="菜品备注" prop="note">
                                    <el-input v-model="basicForm.note" clearable  placeholder="商品备注"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="菜品价格" prop="price">
                                    <el-input v-model="basicForm.price" clearable  placeholder="商品基础价格"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="4">
                                <el-form-item label="是否促销">
                                    <el-switch v-model="isPromotion" @change="changeSwitchPromotion"></el-switch>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <div id="promotionPriceDiv" style="display: none;">
                                <el-form-item label="促销价格" prop="promotionPrice">
                                    <el-input v-model="basicForm.promotionPrice" clearable  placeholder="商品促销价格"></el-input>
                                </el-form-item>
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="餐盒费用" prop="lunchboxPrice">
                                    <el-input v-model="basicForm.lunchboxPrice" clearable  placeholder="餐盒费用"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="上下架" prop="state">
                                    <el-radio-group v-model="basicForm.state" >
                                        <el-radio :label="1">上架</el-radio>
                                        <el-radio :label="2">下架</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="所属商户" prop="vendorUuid">
                                    <el-select placeholder="所属商户" v-model="basicForm.vendorUuid" clearable class="z_select-holder" @change="vendorSelect">
                                        <el-option v-for="vendor in vendorList"
                                                   :key="vendor.uuid"
                                                   :label="vendor.vendorName"
                                                   :value="vendor.uuid">
                                        </el-option>
                                    </el-select>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="菜品分类" prop="categoryUuid">
                                    <el-select placeholder="菜品分类" size="small" v-bind:disabled="normalCateDisabled" v-model="basicForm.categoryUuid" clearable class="z_select-holder" @visible-change="validateVendor">
                                        <el-option v-for="cate in normalCateList"
                                                   :key="cate.uuid"
                                                   :label="cate.name"
                                                   :value="cate.uuid">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="推荐分类"  prop="recommendCategoryUuid">
                                    <el-select placeholder="推荐分类" size="small"  v-bind:disabled="recommendCateDisabled" v-model="basicForm.recommendCategoryUuid" clearable class="z_select-holder" @visible-change="validateVendor">
                                        <el-option v-for="cate in recommendCateList"
                                                   :key="cate.uuid"
                                                   :label="cate.name"
                                                   :value="cate.uuid">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="菜品标签"  prop="tag">
                                    <el-radio-group v-model="basicForm.tag" size="mini" >
                                        <el-radio v-for="(item,index) in tagList"
                                                  size="small"
                                                  style="margin-left: 5px;"
                                                  border
                                                  :key="item.uuid"
                                                  :label="item.uuid">
                                            {{item.name}}
                                        </el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <h3 class="edit-form-title">口味</h3>
                        <el-row>
                            <el-col :span="4">
                                <el-form-item label="口味1">
                                <el-input v-model="basicForm.extendStr[0]" clearable  placeholder="例：不辣"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="4">
                                <el-form-item label="口味2">
                                <el-input v-model="basicForm.extendStr[1]"  clearable placeholder="例：不辣"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="4">
                                <el-form-item label="口味3">
                                    <el-input v-model="basicForm.extendStr[2]"  clearable placeholder="例：微辣"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="4">
                                <el-form-item label="口味4">
                                    <el-input v-model="basicForm.extendStr[3]" clearable  placeholder="例：中辣"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="4">
                                <el-form-item label="口味5">
                                    <el-input v-model="basicForm.extendStr[4]" clearable  placeholder="例：重辣"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="4">
                                <el-form-item label="口味6">
                                    <el-input v-model="basicForm.extendStr[5]"  clearable placeholder="例：变态辣"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <h3 class="edit-form-title">多规格</h3>
                        <div style="margin-left: 48px;">
                            <div class="popover_hover switch_title">
                                是否有多种规格
                                <el-switch v-model="basicForm.spec" @change="changeSwitch"></el-switch>
                            </div>
                            <div v-show="!basicForm.spec">
                            </div>
                            <div v-show="basicForm.spec">
                                <div class="z-tables">
                                    <el-table ref="multipleTable" :data="basicForm.specData" style="width: 100%;">
                                        <el-table-column type="index" width="55" label="序号"></el-table-column>
                                        <el-table-column label="规格名称" min-width="130">
                                            <template slot-scope="scope">
                                                <el-form-item :prop="'specData.' + scope.$index + '.name'" :rules="{required: true, message: '规格名称不能为空', trigger: 'blur'}" :inline-message="true" label-width="0" class="el-form-inline-bottom">
                                                    <el-input v-model="scope.row.name" clearable  placeholder="规格名称，最多20个字"></el-input>
                                                </el-form-item>
                                            </template>
                                        </el-table-column>

                                        <el-table-column label="价格" min-width="130">
                                            <template slot-scope="scope">
                                                <el-form-item :prop="'specData.' + scope.$index + '.price'" :rules="[{required: true, message: '价格不能为空', trigger: 'blur'}]" :inline-message="true" label-width="0" class="el-form-inline-bottom">
                                                    <el-input v-model="scope.row.price" clearable  placeholder="规格价格"></el-input>
                                                </el-form-item>
                                            </template>
                                        </el-table-column>

                                        <el-table-column label="是否默认规格" min-width="130">
                                            <template slot-scope="scope">
                                                <el-switch v-model="scope.row.default" @change="setDefault($event,scope.$index)"></el-switch>
                                            </template>
                                        </el-table-column>

                                        <el-table-column label="操作" min-width="60">
                                            <template slot-scope="scope">
                                                <el-button type="text" @click="removeFormat(scope.$index, scope.row)">删除</el-button>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                </div>
                                <el-button type="text" @click="addFormat">继续添加</el-button>
                            </div>
                        </div>
                        <!--<div class="edit-button-fixed">
                            <div class="edit-button z-yuan-butn">
                                <el-button type="primary" @click="saveProduct">保存回到列表页</el-button>
                                <el-button>返回</el-button>
                            </div>
                        </div>-->
                    </el-form>
                </div>
            </div>
            <!-- 商品基础信息 end -->

            <!-- 图片与商品详情 -->
            <div class="tab-pane" id="productPic" v-cloak>
                <div class="title_pt_25">
                    <h3 class="edit-form-title">商品图片<small>（最多可添加5张图片，建议图片尺寸800*800px，大小≤2MB，支持JPG、PNG、JPEG）</small></h3>
                    <ol class="clearfix ml_50 productPicList">
                        <li v-for="(item,index) in uploadImage.fileList" class="upload-image-box" style="width:150px;height:150px;">
                            <div class="upload-image">
                                <img :src="item.url">
                                <span class="upload-operate upload-operate-delect" @click.stop="delectImage('uploadImage',index,item.url)">点击删除</span>
                            </div>
                        </li>
                        <li class="upload-image-box" @click="dialogImageVisible = true" style="width:150px;height:150px;">
                            <span class="upload-button">
                                <i class="el-icon-upload"></i>
                                添加图片
                            </span>
                        </li>
                    </ol>
                </div>

                <!-- 上传图片模态框 -->
                <el-dialog title="上传文件" :visible.sync="dialogImageVisible">
                    <el-upload
                            ref="upload"
                            action="/fastdfs/file/uploadFile"
                            :show-file-list="false"
                            :on-change="handleChange"
                            :on-success="handleSuccess"
                            :auto-upload="true"
                            :limit=5
                            :on-exceed="handleExceed"
                            :file-list="uploadImage.fileList"
                            :before-upload="beforeAvatarUpload">
                        <el-button size="medium">+&nbsp;点击选择图片</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传JPG/PNG/JPEG文件，且不超过2M</div>
                    </el-upload>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogImageVisible = false">取 消</el-button>
                    </div>
                </el-dialog>
                <!-- 上传图片模态框 end -->
            </div>
            <!-- 图片与商品详情 end -->
            <div class="edit-button-fixed">
                <div class="edit-button z-yuan-butn">
                    <button type="button" class="el-button el-button--primary" onclick="productBasic.saveProduct()">
                        <span>保存回到列表页</span>
                    </button>
                    <button type="button" class="el-button el-button--default" onclick="productBasic.goBack()">
                        <span>返回</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

</div>
</body>
<script charset="utf-8" src="kindeditor/kindeditor-min.js" th:src="@{/kindeditor/kindeditor-min.js}"></script>
<script charset="utf-8" src="kindeditor/lang/zh-CN.js" th:src="@{/kindeditor/lang/zh-CN.js}"></script>
<script th:inline="javascript">
    // 商品基础信息数据初始化Vue
    productBasic = new Vue({
        el: "#productBasic",
        data: {
            isPromotion:false,
            // 商户列表
            vendorList:[[${vendorList}]],
            // 菜品分类下拉框的可用状态
            normalCateDisabled:true,
            recommendCateDisabled:true,
            // form 表单数据,对应ProductInteractiveDTO
            basicForm: {
                // 基础信息
                name: '',//商品名称
                state: 1,//上下架状态
                note: '',//商品备注
                tag: '',//商品标签
                price:'',//商品基础价格
                promotionPrice:'',
                lunchboxPrice:'',
                categoryUuid:'',//商品分类uuid
                recommendCategoryUuid:'',
                vendorUuid:'',//商品所属商户uuid
                // 扩展字段菜品口味(对应菜品非规格属性)
                extendStr:['','','','','',''],
                // 商品是否多规格
                spec: false,
                // 多规格值表格数据内容
                specData: [],
                // 商品的多图片url数组
                mutipicture:[],
            },
            // 加载菜品普通分类,供选择
            normalCateList: [],
            // 加载菜品推荐分类,供选择
            recommendCateList:[],
            // 加载菜品标签,供选择
            tagList:[[${tagList}]],
            // form 表单验证规则（定义商品主信息各个字段的校验规则）
            basicRules: {
                vendorUuid:[
                    { required: true, message: '请选择所属商户', trigger: 'blur' },
                ],
                categoryUuid:[
                    { required: true, message: '请选择商品分类', trigger: 'blur' },
                ],
                name: [
                    { required: true, message: '商品名称不能为空', trigger: 'blur' },
                    { max: 20, message: '长度最多20个字符', trigger: 'blur' }
                ],
                note: [
                    { max: 50, message: '长度最多50个字符', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '价格不能为空', trigger: 'blur' },
                    {
                        validator: function (rule, value, callback) {
                            var MobileRegex = /^\d+\.?\d{0,2}$/;
                            if (value!="" && !MobileRegex.test(value)) {
                                callback(new Error('请输入小数，保留小数点后两位'))
                            } else {
                                callback();
                            }
                        }, trigger: 'blur'
                    }
                ],
                promotionPrice: [
                    {
                        validator: function (rule, value, callback) {
                            var MobileRegex = /^\d+\.?\d{0,2}$/;
                            if (value!="" && !MobileRegex.test(value)) {
                                callback(new Error('请输入小数，保留小数点后两位'))
                            } else {
                                callback();
                            }
                        }, trigger: 'blur'
                    }
                ],
                lunchboxPrice: [
                    { required: true, message: '餐盒价格不能为空', trigger: 'blur' },
                    {
                        validator: function (rule, value, callback) {
                            var MobileRegex = /^\d+\.?\d{0,2}$/;
                            if (value!="" && !MobileRegex.test(value)) {
                                callback(new Error('请输入小数，保留小数点后两位'))
                            } else {
                                callback();
                            }
                        }, trigger: 'blur'
                    }
                ]
            }
        },
        computed: {},
        methods: {
            // 选择菜品分类时，要判断是否选择了商户，如果没选，则提示
            validateVendor:function(show){
                if(show){
                    if(this.basicForm.vendorUuid==""||this.basicForm.vendorUuid==undefined){
                        this.$message({
                            duration: 1500,
                            message: '请先选择所属商户!',
                            type: 'waring',
                            customClass: 'message-center'
                        });
                    }
                }
            },
            // 保存商品的方法（包括基本信息，图片信息，口味信息，多规格信息）
            saveProduct: function () {
                let self = this;
                self.$refs['basicForm'].validate((valid) => {
                    if (valid) {
                        self.loading = true;
                        $.ajax({
                            url: "/backstage/cater/product/save",
                            type: "POST",
                            data: JSON.stringify(self.basicForm),
                            contentType: "application/json;charset=UTF-8",
                            dataType: "json",
                            success: function (data) {
                                if (data && data.returnCode == "1") {
                                    self.$message({
                                        showClose: true,
                                        duration: 1500,
                                        message: '发布菜品成功',
                                        type: 'success',
                                        customClass: 'message-center',
                                        onClose: function () {
                                            window.location.href = "/backstage/cater/product/tolist?vendorUuid="+self.vendorUuid;
                                        }
                                    });
                                } else {
                                    self.$message({
                                        showClose: true,
                                        duration: 1500,
                                        message: '新增会员失败',
                                        type: 'error',
                                        customClass: 'message-center'
                                    });
                                    self.loading = false;
                                }
                            },
                            error: function () {
                                self.$message({
                                    showClose: true,
                                    duration: 1500,
                                    message: '系统异常，请联系管理员',
                                    type: 'error',
                                    customClass: 'message-center'
                                });
                                self.loading = false;
                            }
                        });
                    }
                });
            },
            //返回列表
            goBack:function(){
                window.location.href = "/backstage/cater/product/tolist";
            },
            // 筛选条件选择商户后，加载出商户下的桌台类型
            vendorSelect: function () {
                var self = this;
                // 获取当前选中的商户uuid
                let vendorUuid = self.basicForm.vendorUuid;
                $.ajax({
                    url: "/backstage/cater/productcate/listByVendorUuid?vendorUuid="+vendorUuid,
                    type: "POST",
                    success: function(data) {
                        if (data && data.returnCode == "1") {
                            // 加载普通分类
                            self.normalCateList = data.returnMessage.normalCateList;
                            // 加载推荐分类
                            self.recommendCateList = data.returnMessage.recommendCateList;
                            self.normalCateDisabled = false;
                            self.recommendCateDisabled = false;
                        }
                    }
                });
            },
            // 删除行数据
            handleDelete(index, row) {
                console.log(index, row);
            },
            /** 商品多规格处理函数 start */
            // 是否是多规格商品的开关，如果打开，则添加一行，如果不是，则删除所有行
            changeSwitch(switchValue){
                if(switchValue){
                    this.basicForm.specData=[{
                        name: '',//规格名称
                        price: '',//规格价格
                        default:false,
                    }];
                }else{
                    this.basicForm.specData=[];
                }
            },
            changeSwitchPromotion(switchValue){
                if(switchValue){
                    $("#promotionPriceDiv").css("display","block");
                }else{
                    $("#promotionPriceDiv").css("display","none");
                    this.basicForm.promotionPrice = '';
                }
            },
            // 删除多规格数据方法
            removeFormat(index, row) {
                if (index !== -1) {
                    this.basicForm.specData.splice(index, 1)
                }
            },
            // 新增多规格数据方法
            addFormat() {
                this.basicForm.specData.push({
                    name: '',
                    price: '',
                    default:false,
                });
            },
            // 选择了一个规格作为默认规格，其他的规则要关闭默认,value是当前switch的状态值，index是当前行数
            setDefault(value,index){
                if(value){
                    let specData = this.basicForm.specData;
                    specData.forEach(function(c,index1){
                        if(index!=index1) {
                            c.default = false;
                        }
                    });
                }
            }
            /** 商品多规格处理函数 end */
        }
    });

    // 商品图片信息初始化Vue
    new Vue({
        el: "#productPic",
        data: {
            // 上传图片模态框
            dialogImageVisible: false,
            // 上传图片数据
            uploadImage: {
                imageUrl: '',
                fileList: []
            }
        },
        methods: {
            // 图片上传前校验
            beforeAvatarUpload(file) {
                console.info(file.type);
                const isJPEG = file.type === 'image/jpeg';
                const isJPG = file.type === 'image/jpg';
                const isPNG = file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!(isJPG||isJPEG||isPNG)) {
                    this.$message.error('上传图片只能是JPG/PNG/JPEG格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 2MB!');
                }
                return (isJPG||isJPEG||isPNG) && isLt2M;
            },
            handleSuccess(response,file,fileList){
                console.info(response);
                //将response中的url设置到productBasic的mutiPicture数组中
                let mutiurl = productBasic.basicForm.mutipicture;
                let length = mutiurl.length;
                mutiurl[length]=response.fdfsIpPre+response.fullPath;
                let files = this.uploadImage.fileList;
                let length1 = files.length;
                files[length1] = {"url":response.fdfsIpPre+response.fullPath};
                this.dialogImageVisible = false;
            },
            // 图片状态变化监听,选择图片后执行的事件
            handleChange(file, fileList) {
                //this.uploadImage.fileList = fileList.slice(-1);
                //this.uploadImage.fileList = fileList;
                //this.uploadImage.imageUrl = URL.createObjectURL(file.raw);
                //this.dialogImageVisible = false;
            },
            // 上传的图片超出数量后，提示
            handleExceed(files,fileList){
                this.$message.error('上传图片不能超过5张!');
            },
            // 删除图片事件
            delectImage(fileName,index,url){
                // 使用splice方法删除数组中的元素
                let arr = productBasic.basicForm.mutipicture;
                let files = this.uploadImage.fileList;
                let position = $.inArray(url,arr);
                arr.splice(position,1);
                files.splice(position,1);
                //this[fileName].fileList = [];
                //this[fileName].imageUrl = '';
            }
        }
    })

    // 多规格弹出框显示事件
    function showoption(index){
        $(".multi-box:eq("+index+")").find(".option-select-box").slideDown().end().siblings().find(".option-select-box").slideUp();
    }

    // 多规格弹出框隐藏事件
    function hideoption(index){
        $(".multi-box:eq("+index+")").find(".option-select-box").slideUp();
    }

    // 商品新增tab切换
    $(".z-tabs_header .z-tabs_item").click(function(){
        $(this).addClass("router-link-active").siblings().removeClass("router-link-active");
        $(".tab-content .tab-pane").eq($(this).index()).addClass("active").siblings().removeClass("active");
    })
</script>
</html>
